/**
 * @fileOverview add node by mouse
 * @author huangtonger@aliyun.com
 */
const Page = require('../../base/');
const Util = require('../util/');
// const Global = require('../global');

Page.registerBehaviour('dragPanelItemAddNode', diagram => {
  const graph = diagram.getGraph();
  const rootGroup = graph.getRootGroup();
  let startBox;
  let delegation;
  let nodeSize;
  let addType;
  let addModel;

  graph.behaviourOn('canvas:mouseenter', ev => {
    if (!delegation) {
      addType = diagram.get('addType');
      addModel = diagram.get('addModel');
      addModel = Util.clone(addModel);
      if (addType === 'node') {
        nodeSize = Util.getNodeSize(addModel.size);
        const halfWidth = nodeSize[0] / 2;
        const halfHeight = nodeSize[1] / 2;
        startBox = {
          minX: ev.x - halfWidth,
          minY: ev.y - halfHeight,
          maxX: ev.x + halfWidth,
          maxY: ev.y + halfHeight,
          width: nodeSize[0],
          height: nodeSize[1]
        };
        delegation = diagram.getDelegation([ startBox ], rootGroup);
        diagram.setSignal('panningItem', true);
        diagram.set('panItemDelegation', delegation);
        diagram.set('panItemStartBox', startBox);
        diagram.set('panItemStartPoint', {
          x: ev.x,
          y: ev.y
        });
      }
    }
  });
  graph.behaviourOn('mouseup', ev => {
    if (!delegation) {
      return;
    }
    addModel.x = ev.x;
    addModel.y = ev.y;
    const type = addType;
    Util.setId(addModel);
    const editor = diagram.editor;
    delegation.remove();
    diagram.endAdd();
    diagram.clearAlignLine();
    diagram.clearSelected();
    diagram.focusGraphWrapper();
    if (editor) {
      editor.executeCommand('add', {
        type: 'node',
        addModel
      });
    } else {
      graph.add(type, addModel);
    }
    diagram.setSelected(graph.find(addModel.id), true);
    resetStatus();
  });
  graph.behaviourOn('canvas:mouseleave', () => {
    if (!delegation) {
      return;
    }
    diagram.clearAlignLine();
    delegation.remove();
    graph.draw();
    diagram.cancelAdd();
    resetStatus();
  });
  function resetStatus() {
    diagram.setSignal('panningItem', false);
    diagram.set('panItemDelegation', undefined);
    diagram.set('panItemStartBox', undefined);
    diagram.set('panItemStartPoint', undefined);
    delegation = undefined;
    nodeSize = undefined;
    addType = undefined;
    addModel = undefined;
  }
}, [ 'processPanItem' ]);
